<?php
// +----------------------------------------------------------------------
// | APP版本
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------
namespace app\event\app;

use app\common\event\Base;
use app\event\app\Rebate as RebateEvent;
use app\event\ucenter\User as UserEvent;
use app\model\app\ExchangeCouponOrder as ExchangeCouponOrderModel;
use app\model\app\TbkShare as TbkShareModel;
use app\model\app\TbkOrder as TbkOrderModel;
use app\model\app\TbkPrivilege as TbkPrivilegeModel;
use app\model\app\TbkGood as TbkGoodModel;
use app\model\app\TbkPid as TbkPidModel;
use app\model\app\TbkPidUser as TbkPidUserModel;
use app\model\ucenter\User as UserModel;
use app\model\ucenter\UserMoneyLog as UserMoneyLogModel;
use app\model\ucenter\UserTask as UserTaskModel;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\helper\Str;

class Tbk extends Base
{

    protected function setClient($client)
    {
        $client->setAppKey('675107a00b163');
        $client->setAppSecret('959b15cb9c214df2e8ebe9defa0aeb69');
        $client->setVersion('v3.0.0');
    }


    /**
     * 补单
     * @param $order
     * @param $user
     * @return array
     */
    public function supplement($order, $user)
    {
        try {
            if (!$order) {
                throw new Exception('订单异常');
            }
            $order['user_id'] = $user['id'];
            $order->save();

            $this->_payFee($order);
            $result['code'] = 0;
        } catch (\Exception $e) {
            // 回滚事务
            $result = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $result;
    }

    public function getRefundOrder($time, $old_time = 1800)
    {
        try {
            require_once app()->getRootPath() . 'extend/dtk/DtkClient.php';
            require_once app()->getRootPath() . 'extend/dtk/GetTipList.php';
            require_once app()->getRootPath() . 'extend/dtk/GetTbParseContent.php';
            require_once app()->getRootPath() . 'extend/dtk/GetPrivilegeLink.php';
            require_once app()->getRootPath() . 'extend/dtk/GetRefundOrderList.php';
            //订单详情
            $client = new \GetRefundOrderList();
            $this->setClient($client);

            $param['pageSize'] = 100;
            $param['searchType'] = 3;
            $param['pageNo'] = 1;
            $param['bizType'] = 1;
            $param['refundType'] = 0;
            $param['startTime'] = time_format($time);
            $res = $client->setParams($param)->request();
            $res = json_decode($res, true);
            dump($param);
            dump($res);exit();
            if ($res['code'] == 0 && isset($res['data']['results'])) {
                foreach ($res['data']['results'] as $index => $result) {
                    foreach ($result as $k => $trade) {
                        $tbk = TbkOrderModel::where('trade_id', $trade['trade_id'])->find();
                        if (!$tbk) {
                            $tbk = TbkOrderModel::create($trade);
                            if ($tbk && $tbk['alipay_total_price'] > 0) {

                                $pidUser = TbkPidUserModel::where('pid', 'like', '%' . $tbk['adzone_id'])
                                    ->where('seller_shop_title', $tbk['seller_shop_title'])
                                    ->order('use_time DESC')
                                    ->find();
                                if (!$pidUser) {
                                    continue;
                                }
                                $user = UserModel::where('id', $pidUser['user_id'])->find();
                                if (!$user) {
                                    continue;
                                }
                                $tbk['user_id'] = $user['id'];
                                $tbk->save();
                                $this->_payFee($tbk);
                            }

                        } elseif ($tbk['modified_time'] != $trade['modified_time']) {
                            $tbk['modified_time'] = $trade['modified_time'];//已付款：指订单已付款，但还未确认收货
                            $tbk['tk_status'] = $trade['tk_status'];//已付款：指订单已付款，但还未确认收货
                            if (!$tbk['receive_time'] && ($trade['tk_status'] == 3 || $trade['tk_status'] == 14)) {
                                $tbk['receive_time'] = $trade['modified_time'];
                            }
                            if (isset($trade['tk_earning_time'])) {
                                $tbk['tk_earning_time'] = $trade['tk_earning_time'];
                            }
                            // 已收货：指订单已确认收货，但商家佣金未支付 已结算：指订单已确认收货，且商家佣金已支付成功
                            // 已失效：指订单关闭/订单佣金小于0.01元，订单关闭主要有：1）买家超时未付款； 2）买家付款前，买家/卖家取消了订单；3）订单付款后发起售中退款成功；3：订单结算，12：订单付款， 13：订单失效，14：订单成功
                            //
                            // refund_tag维权标签，0 含义为非维权 1 含义为维权订单 维权标签，0 含义为非维权 1 含义为维权订单
                            $tbk->save();
                            $this->_payFee($tbk);
                        }
                    }
                }
            }

            $result = ['code' => 0, 'data' => $res];
        } catch (\Exception $e) {
            // 回滚事务
            $result = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $result;
    }


    /**
     * 获取淘宝订单 https://www.dataoke.com/pmc/api-d.html?id=27
     * @param $time
     * @param $old_time
     */
    public function getOrder($time, $old_time = 1800)
    {
        try {
            require_once app()->getRootPath() . 'extend/dtk/DtkClient.php';
            require_once app()->getRootPath() . 'extend/dtk/GetTipList.php';
            require_once app()->getRootPath() . 'extend/dtk/GetTbParseContent.php';
            require_once app()->getRootPath() . 'extend/dtk/GetPrivilegeLink.php';
            require_once app()->getRootPath() . 'extend/dtk/GetOrderDetails.php';
            //订单详情
            $client = new \GetOrderDetails();
            $this->setClient($client);

            $param['pageSize'] = 100;
            $param['queryType'] = 4;
            $param['startTime'] = time_format($time - $old_time);
            $param['endTime'] = time_format($time);
            $res = $client->setParams($param)->request();
            $res = json_decode($res, true);
            if ($res['code'] == 0 && isset($res['data']['results'])) {
                foreach ($res['data']['results'] as $index => $result) {
                    foreach ($result as $k => $trade) {
                        $tbk = TbkOrderModel::where('trade_id', $trade['trade_id'])->find();
                        if (!$tbk) {
                            $tbk = TbkOrderModel::create($trade);
                            if ($tbk && $tbk['alipay_total_price'] > 0) {

                                $pidUser = TbkPidUserModel::where('pid', 'like', '%' . $tbk['adzone_id'])
                                    ->where('seller_shop_title', $tbk['seller_shop_title'])
                                    ->order('use_time DESC')
                                    ->find();
                                if (!$pidUser) {
                                    continue;
                                }
                                $user = UserModel::where('id', $pidUser['user_id'])->find();
                                if (!$user) {
                                    continue;
                                }
                                $tbk['user_id'] = $user['id'];
                                $tbk->save();
                                $this->_payFee($tbk);
                            }

                        } elseif ($tbk['modified_time'] != $trade['modified_time']) {
                            $tbk['modified_time'] = $trade['modified_time'];//已付款：指订单已付款，但还未确认收货
                            $tbk['tk_status'] = $trade['tk_status'];//已付款：指订单已付款，但还未确认收货
                            if (!$tbk['receive_time'] && ($trade['tk_status'] == 3 || $trade['tk_status'] == 14)) {
                                $tbk['receive_time'] = $trade['modified_time'];
                            }
                            if (isset($trade['tk_earning_time'])) {
                                $tbk['tk_earning_time'] = $trade['tk_earning_time'];
                            }
                            // 已收货：指订单已确认收货，但商家佣金未支付 已结算：指订单已确认收货，且商家佣金已支付成功
                            // 已失效：指订单关闭/订单佣金小于0.01元，订单关闭主要有：1）买家超时未付款； 2）买家付款前，买家/卖家取消了订单；3）订单付款后发起售中退款成功；3：订单结算，12：订单付款， 13：订单失效，14：订单成功
                            //
                            // refund_tag维权标签，0 含义为非维权 1 含义为维权订单 维权标签，0 含义为非维权 1 含义为维权订单
                            $tbk->save();
                            $this->_payFee($tbk);
                        }
                    }
                }
            }

            $result = ['code' => 0, 'data' => $res];
        } catch (\Exception $e) {
            // 回滚事务
            $result = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $result;
    }

    public function test()
    {
        $tbk = TbkOrderModel::where('id',4956)->find();

        dump($tbk->toArray());
        $this->_payFee($tbk);
    }
    protected function _payFee($tbk)
    {
        if (!$tbk['user_id']) {
            return false;
        }
        $user = UserModel::where('id', $tbk['user_id'])->find();
        if (!$user) {
            return false;
        }
        // 退款订单
        $userTask = UsertaskModel::where('relation_id', $tbk['id'])->where('task_type', 22)->find();
        if (!$userTask) {
// 新增任务
            $userTask['task_id'] = 11;
            $userTask['relation_id'] = $tbk['id'];
            $userTask['task_type'] = 22;
            $userTask['user_id'] = $user['id'];
            $userTask['agent_id'] = $user['agent_id'];
            $userTask['title'] = $tbk['item_title'];
            $userTask['logo'] = $tbk['item_img'];
            $userTask['money'] = $tbk['alipay_total_price'];
            $userTask['commission'] = $tbk['pub_share_pre_fee_for_commission'] - $tbk['alimama_share_fee'];
            $userTask['task_no'] = $tbk['trade_id'];
//            $userTask['end_time'] = time() + 30 * 86400;
            $userTask['step'] = $tbk['tk_status'];
            $userTask['submit_info'] = $tbk->toArray();
            $userTask['status'] = 1;
            $userTask = UserTaskModel::create($userTask);
            if (!$userTask) {
                throw new Exception('系统故障');
            }
        }
        $userTask['step'] = $tbk['tk_status'];
        $userTask['commission'] = $tbk['pub_share_pre_fee_for_commission'] - $tbk['alimama_share_fee'];

        if ($tbk['refund_tag'] == 1) {
            // 订单失效。
            $userTask['status'] = 3;
        }
        if ($userTask['step'] == 13) {
            $userTask['status'] = 4;
        } elseif ($tbk['refund_tag'] == 0 && ($userTask['step'] == 14 || $userTask['step'] == 3)) {
            $userTask['status'] = 2;
            // 发放佣金
            $log = UserMoneyLogModel::where('user_id', $userTask['user_id'])->where('type', 39)
                ->where('order_id', $userTask['task_no'])
                ->where('channel', 'tbk')->find();
            if (!$log) {
                UserEvent::exhibitionIncome($user, $userTask['commission'], $userTask['title'], 39, $user['id'], $userTask['task_no'], 0, 'tbk', 11);
            }
        }
        $userTask->save();
        if ($userTask['status'] == 3 || $userTask['status'] == 4) {
            // 失败订单，查询是否扣款
            $log = UserMoneyLogModel::where('user_id', $userTask['user_id'])->where('type', 39)
                ->where('order_id', $userTask['task_no'])
                ->where('channel', 'tbk')
                ->where('is_eversal', 0)
                ->find();
            if ($log) {
                UserEvent::exhibitionIncomeBack($user, '电商返利因退款或退货返佣取消', $user['id'], $userTask['task_no'], 'tbk', 11);
            }
        }
    }

    /**
     * 获取淘宝订单
     * @param $time
     * @param $old_time
     */
    public function parseContent($content, $user, $from)
    {
        try {
            if (!$user) {
                throw new Exception('请先登录');
            }
            require_once app()->getRootPath() . 'extend/dtk/DtkClient.php';
            require_once app()->getRootPath() . 'extend/dtk/GetTipList.php';
            require_once app()->getRootPath() . 'extend/dtk/GetTbParseContent.php';
            require_once app()->getRootPath() . 'extend/dtk/GetPrivilegeLink.php';
            require_once app()->getRootPath() . 'extend/dtk/GetOrderDetails.php';
            //订单详情
            $client = new \GetTbParseContent();
            $this->setClient($client);
//            $pid = TbkPidModel::where('status', 1)->order('use_time ASC')->find();

            $user_pid = TbkPidUserModel::where('user_id', $user['id'])->order('use_time DESC')->whereTime('use_time', '>', '-1 day')->find();
            if (!$user_pid) {
                // 最晚未使用
                $pid = TbkPidModel::where('status', 1)->order('use_time ASC')->find();
                if (!$pid) {
                    throw new Exception('内部错误');
                }
            } else {
                $pid = TbkPidModel::where('id', $user_pid['tbk_pid_id'])->find();
                if (!$pid) {
                    throw new Exception('内部错误');
                }

            }
            if ($pid['status'] == 1) {
                $pid['use_time'] = time_format();
                $pid['count'] = $pid['count'] + 1;
                $pid['user_id'] = null;
                $pid->save();
            }

            $param['pid'] = $pid['pid'];
            $param['content'] = $content;
            $res = $client->setParams($param)->request();
            $data = json_decode($res, true);
            if ($data['code'] == 0 && isset($data['data'])) {
                $insert = [];
                foreach ($data['data'] as $index => $item) {
                    if ($index == 'originInfo') {
                        foreach ($item as $k => $v) {
                            $insert[Str::snake($k)] = $v;
                        }
                    }
                    $insert[Str::snake($index)] = $item;
                }
                $insert['keyword'] = $content;
                if (!$insert['commission_rate']) {
                    throw new Exception('当前商品返利过期或者库存不足');
                }
                $insert['user_id'] = $user['id'];
                $share = TbkShareModel::create($insert);
                $result['code'] = 0;
                $result['data']['share'] = RebateEvent::formatGood($share->toArray(), 'tbk');
                $result['data']['channel'] = 'tbk';
                $result['message'] = '获取成功';
                // 绑定当前商家
                if (!empty($user_pid)) {
                    // 已经绑定当前商家
                    if ($user_pid['seller_shop_title'] == $share['shop_name']) {
                        // 更新使用时间
                        $user_pid['use_time'] = time_format();
                        $user_pid->save();
                    } else {
                        // 是否同pid已经绑定
                        $re = TbkPidUserModel::where('user_id', $user_pid['user_id'])->where('pid', $user_pid['pid'])
                            ->where('seller_shop_title', $share['shop_name'])
                            ->whereNotNull('use_time')
                            ->find();
                        if ($re) {
                            $re['use_time'] = time_format();
                            $re->save();
                        } else {
                            $user_pid = ['user_id' => $user['id'], 'seller_shop_title' => $share['shop_name'], 'tbk_pid_id' => $user_pid['tbk_pid_id'], 'pid' => $user_pid['pid'], 'use_time' => time_format()];
                            TbkPidUserModel::create($user_pid);
                        }
                    }

                } else {
//                    // 增加使用记录
                    $user_pid = ['user_id' => $user['id'], 'seller_shop_title' => $share['shop_name'], 'tbk_pid_id' => $pid['id'], 'pid' => $pid['pid'], 'use_time' => time_format()];
                    TbkPidUserModel::create($user_pid);
                }
            } else {
                $result['code'] = 1;
                $result['message'] = '商品暂无返利';
            }

//            Db::startTrans();
//
//            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $result = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $result;

    }

    /**
     * 每日爆品推荐
     * 应用场景：
     * 用于搭建应用内的营销专区，或在社群内进行分发推广
     * 接口说明：
     * 接口返回每天满足联盟爆品规则的商品合集，单价10~20元商品当日销量超过3000单，20~40元商品当日销量超过1000单，大于等于40元的销量超过500单。 （因为统计的是商品当天的销量，所以早上可能存在数量很少的情况。10分钟会刷新一次）
     * 大淘客的一级分类id，如果需要传多个，以英文逗号相隔，如：”1,2,3”。1 -女装，2 -母婴，3 -美妆，4 -居家日用，5 -鞋品，6 -美食，7 -文娱车品，8 -数码家电，9 -男装，10 -内衣，11 -箱包，12 -配饰，13 -户外运动，14 -家装家纺。不填默认全部
     * @param $time
     * @param $old_time
     */
    public function getExplosiveGoodsList($PriceCid = 1)
    {
        try {

            if (Cache::get('getExplosiveGoodsList' . $PriceCid)) {
                $result['data'] = Cache::get('getExplosiveGoodsList' . $PriceCid);
            }
            require_once app()->getRootPath() . 'extend/dtk/DtkClient.php';
            require_once app()->getRootPath() . 'extend/dtk/GetTipList.php';
            require_once app()->getRootPath() . 'extend/dtk/GetExplosiveGoodsList.php';

            //订单详情
            $client = new \GetExplosiveGoodsList();
            $this->setClient($client);
            $param['pageId'] = 1;
            $param['pageSize'] = 3;
            $param['PriceCid'] = $PriceCid;
            $res = $client->setParams($param)->request();
            $data = json_decode($res, true);
            if ($data['code'] == 0 && isset($data['data']['list'])) {
                Cache::set('getExplosiveGoodsList' . $PriceCid, $data['data']['list'], 600);
                $result['data'] = $data['data']['list'];
            }
            $result['code'] = 0;
        } catch (\Exception $e) {
            // 回滚事务
            $result = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $result;

    }

    /**
     * 各大榜单
     * 应用场景：
     * 可用于应用内的榜单栏目，搭建个性化榜单。帮助用户快速决策并下单，提升选品体验
     * 接口说明：
     * 接口返回大淘客平台八大榜单（必推榜、实时榜、低价高佣榜、全天销量榜、热推榜、综合热搜榜）前200条商品数据（必推榜100条）。 建议每5分钟请求一次。 注意：不同榜单接口数据可能有差异，请以实际返回为准。
     * rankType榜单类型：1.实时榜 ，2.全天榜，3.热推榜，7.综合热搜榜，8.原实时榜2.0（已升级为实时榜），9.必推榜，11.昨日销量榜，12.7日销量榜，13.30日销量榜，14.去年同期销量榜，15.低价高佣榜。红色为2024/05/15新增榜单
     * 大淘客的一级分类id，如果需要传多个，以英文逗号相隔，如：”1,2,3”。1 -女装，2 -母婴，3 -美妆，4 -居家日用，5 -鞋品，6 -美食，7 -文娱车品，8 -数码家电，9 -男装，10 -内衣，11 -箱包，12 -配饰，13 -户外运动，14 -家装家纺。不填默认全部
     * @param $time
     * @param $old_time
     */
    public function getRankingList($rankType = 1, $page = 1)
    {
        try {

            if (Cache::get('get_ranking_list' . $rankType . $page)) {
                $result['data'] = Cache::get('get_ranking_list' . $rankType . $page);
            } else {
                require_once app()->getRootPath() . 'extend/dtk/DtkClient.php';
                require_once app()->getRootPath() . 'extend/dtk/GetTipList.php';
                require_once app()->getRootPath() . 'extend/dtk/GetRankingList.php';

                //订单详情
                $client = new \GetRankingList();
                $this->setClient($client);
                $param['pageId'] = $page;
                $param['pageSize'] = 50;
                $param['rankType'] = $rankType;
                $res = $client->setParams($param)->request();
                $data = json_decode($res, true);
                if ($data['code'] == 0 && isset($data['data'])) {
                    $lists = $data['data'];
                    $cache = [];
                    foreach ($lists as $list) {
                        if (!strpos($list['dtitle'], '避孕')) {
                            $cache[] = $list;
                        };
                    }
                    Cache::set('get_ranking_list' . $rankType . $page, $cache, 600);
                    $result['data'] = $cache;
                }
            }
            $result['code'] = 0;
        } catch (\Exception $e) {
            // 回滚事务
            $result = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $result;

    }

    /**
     * 各大榜单
     * 应用场景：
     * 可用于应用内的榜单栏目，搭建个性化榜单。帮助用户快速决策并下单，提升选品体验
     * 接口说明：
     * 接口返回大淘客平台八大榜单（必推榜、实时榜、低价高佣榜、全天销量榜、热推榜、综合热搜榜）前200条商品数据（必推榜100条）。 建议每5分钟请求一次。 注意：不同榜单接口数据可能有差异，请以实际返回为准。
     * rankType榜单类型：1.实时榜 ，2.全天榜，3.热推榜，7.综合热搜榜，8.原实时榜2.0（已升级为实时榜），9.必推榜，11.昨日销量榜，12.7日销量榜，13.30日销量榜，14.去年同期销量榜，15.低价高佣榜。红色为2024/05/15新增榜单
     * 大淘客的一级分类id，如果需要传多个，以英文逗号相隔，如：”1,2,3”。1 -女装，2 -母婴，3 -美妆，4 -居家日用，5 -鞋品，6 -美食，7 -文娱车品，8 -数码家电，9 -男装，10 -内衣，11 -箱包，12 -配饰，13 -户外运动，14 -家装家纺。不填默认全部
     * @param $time
     * @param $old_time
     */
    public function searchByKeyword($keyword, $user, $page = 1)
    {
        try {

            require_once app()->getRootPath() . 'extend/dtk/DtkClient.php';
            require_once app()->getRootPath() . 'extend/dtk/GetTipList.php';
            require_once app()->getRootPath() . 'extend/dtk/GetTbServiceSearch.php';

            //订单详情
            $client = new \GetTbServiceSearch();
            $this->setClient($client);
            $user_pid = TbkPidUserModel::where('user_id', $user['id'])->order('use_time DESC')->whereTime('use_time', '>', '-1 day')->find();
            if (!$user_pid) {
                // 最晚未使用
                $pid = TbkPidModel::where('status', 1)->order('use_time ASC')->find();
                if (!$pid) {
                    throw new Exception('内部错误');
                }
            } else {
                $pid = TbkPidModel::where('id', $user_pid['tbk_pid_id'])->find();
                if (!$pid) {
                    throw new Exception('内部错误');
                }

            }
            if ($pid['status'] == 1) {
                $pid['use_time'] = time_format();
                $pid['count'] = $pid['count'] + 1;
                $pid['user_id'] = null;
                $pid->save();
            }

            $param['pid'] = $pid['pid'];
            $param['keyWords'] = $keyword;
            $param['pageSize'] = 50;
            $param['pageNo'] = $page;
            $param['source'] = 1;
            $res = $client->setParams($param)->request();
            $data = json_decode($res, true);
            $goods = [];
            if ($data['code'] == 0 && isset($data['data']) && count($data['data']) > 0) {
                foreach ($data['data'] as $k => $v) {
                    $v['channel'] = 'tbk';
                    $goods[] = $v;
                }
            }
            $result['code'] = 0;
            $result['data'] = $goods;
        } catch (\Exception $e) {
            // 回滚事务
            $result = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $result;

    }

    /**
     * 获取淘宝订单
     * @param $time
     * @param $old_time
     */
    public function privilegeLink($goodsId)
    {

        require_once app()->getRootPath() . 'extend/dtk/DtkClient.php';
        require_once app()->getRootPath() . 'extend/dtk/GetTipList.php';
        require_once app()->getRootPath() . 'extend/dtk/GetTbParseContent.php';
        require_once app()->getRootPath() . 'extend/dtk/GetPrivilegeLink.php';
        require_once app()->getRootPath() . 'extend/dtk/GetOrderDetails.php';
        //订单详情
        $client = new \GetPrivilegeLink();

        $this->setClient($client);

        $param['goodsId'] = $goodsId;
        $param['promtionType'] = 2;
        $res = $client->setParams($param)->request();
        $data = json_decode($res, true);
        $insert = [];
        $insert['goods_id'] = $goodsId;
        foreach ($data['data'] as $index => $item) {
            if ($index == 'originInfo') {
                foreach ($item as $k => $v) {
                    $insert[Str::snake($k)] = $v;
                }
            }
            $insert[Str::snake($index)] = $item;
        }
        TbkPrivilegeModel::create($insert);
        return json_decode($res, true);
    }

    /**
     * 获取淘宝订单
     * @param $time
     * @param $old_time
     */
    public function heightCommission($sort = 1)
    {

        require_once app()->getRootPath() . 'extend/dtk/DtkClient.php';
        require_once app()->getRootPath() . 'extend/dtk/GetTipList.php';
        require_once app()->getRootPath() . 'extend/dtk/GetTbParseContent.php';
        require_once app()->getRootPath() . 'extend/dtk/GetPrivilegeLink.php';
        require_once app()->getRootPath() . 'extend/dtk/GetListHeightCommission.php';
        //订单详情
        $client = new \GetListHeightCommission();

        $this->setClient($client);

        $param['pageSize'] = 100;
//        $param['cid'] = 1;
        $param['pageId'] = 1;
        $param['sort'] = $sort;
        $res = $client->setParams($param)->request();
        $data = json_decode($res, true);
        foreach ($data['data']['list'] as $index => $good) {
            $insert = [];
            foreach ($good as $index_g => $item) {
                $insert[Str::snake($index_g)] = $item;

            }
            $insert['da_id'] = $insert['id'];
            unset($insert['id']);
            $has = TbkGoodModel::where('da_id', $insert['da_id'])->find();
            if ($has) {
                $has->save($insert);
            } else {
                TbkGoodModel::create($insert);
            }
        }
        return json_decode($res, true);
    }

    public function endPay($param)
    {
        try {
            $order = ExchangeCouponOrderModel::where('sn', $param['external_orderno'])->where('status', 1)->find();
            if (!$order) {
                throw new Exception('兑换不存在');
            }
            Db::startTrans();
            $order->allowField(['status', 'order_sn', 'msg', 'mobile', 'name', 'actual_price', 'pay_price', 'img', 'kami'])
                ->save($param);
            $task = UserTaskModel::where('task_type', 21)->where('relation_id', $order['id'])->find();
            if (!$task) {
                throw new Exception('任务不存在');
            }
            $task['step'] = $order['status'];
            if ($order['status'] == 4) {
                $task['status'] = 2;
            } elseif ($order['status'] == 3 || $order['status'] == 2) {
                $task['status'] = 1;
            } else {
                $task['reason'] = '接口异常' . $order['msg'];
                $task['status'] = 3;
            }
            $task->save();
            if ($task['status'] == 2) {
                $user = UserModel::where('id', $task['user_id'])->find();
                if ($user) {
                    UserEvent::exhibitionIncome($user, $task['commission'], $task['title'], 38, $user['id'], $task['task_no'], 0, $order['branch_id'], 13);
                }
            }
            Db::commit();
            $rep = ['code' => 0, 'message' => '接收成功'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }


}
